package cc.rengu.igas.channel.wechat.core.service.trans;

import cc.rengu.igas.channel.wechat.common.constant.WechatConfigConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatParamConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatServiceConstant;
import cc.rengu.igas.channel.wechat.common.constant.WechatTreeNodeConstant;
import cc.rengu.igas.channel.wechat.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.wechat.common.enums.TemplateTypeEnum;
import cc.rengu.igas.channel.wechat.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.wechat.core.model.bean.Keyword;
import cc.rengu.igas.channel.wechat.core.model.bean.WechatMsgPushBean;
import cc.rengu.igas.channel.wechat.core.service.base.MsgPushService;
import cc.rengu.igas.channel.wechat.facade.request.CheckFailMsgPushRequest;
import cc.rengu.igas.channel.wechat.facade.response.CheckFailMsgPushResponse;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.MsgTemplateCfgMapper;
import cc.rengu.oltp.service.common.dao.impl.MsgTemplateCfgMapperImpl;
import cc.rengu.oltp.service.common.entity.DstChannelCfg;
import cc.rengu.oltp.service.common.entity.MsgTemplateCfg;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.RedisUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

/**
 * 审核未通过通知
 */
public class CheckFailMsgPushService extends MsgPushService {
    @Override
    protected Object beforeBizProcess() throws Exception {
        CheckFailMsgPushRequest checkFailMsgPushRequest = new CheckFailMsgPushRequest();
        ConvertUtil.convertOutput(checkFailMsgPushRequest);
        return checkFailMsgPushRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        int iReturnCode = 0;
        CheckFailMsgPushResponse checkFailMsgPushResponse = new CheckFailMsgPushResponse();
        CheckFailMsgPushRequest checkFailMsgPushRequest = (CheckFailMsgPushRequest) request;
        DstChannelCfg dstChannelCfg = (DstChannelCfg) xmlTreeUtil.getXmlTreeObjectValue(WechatTreeNodeConstant.DST_CHANNEL_CFG, DstChannelCfg.class);

        /*从redis缓存获取accessToken*/
        String accessToken = RedisUtil.onceGet(WechatParamConstant.ACCESS_TOKEN_CACHE_NAME + dstChannelCfg.getSubAppId());
        if (accessToken == null) {
            accessToken = getAccessToken(dstChannelCfg);
        }
        MsgTemplateCfgMapper templateCfgMapper = new MsgTemplateCfgMapperImpl();
        MsgTemplateCfg templateCfg = templateCfgMapper.selectMsgTemplateCfgByTemplateType(checkFailMsgPushRequest.getHeader().getInstId(),
                TemplateTypeEnum.MSG10.getTypeCode());
        if (templateCfg == null) {
            throw new BizException(RespCodeEnum.TEMPLATE_CFG_NOT_EXIST.getRespCode(), RespCodeEnum.TEMPLATE_CFG_NOT_EXIST.getRespDesc());
        }
        if (templateCfg.getTemplateDesc() == null || templateCfg.getTemplateDesc().isEmpty()) {
            rglog.error("获取微信消息推送firstdata失败，请配置");
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }

        WechatMsgPushBean wechatMsgPushBean = new WechatMsgPushBean();
        Keyword keyword = new Keyword();
        keyword.setKeyValue(templateCfg.getTemplateDesc());
        wechatMsgPushBean.setFirst(keyword);
        keyword = new Keyword();
        keyword.setKeyValue(checkFailMsgPushRequest.getMchntNo());
        wechatMsgPushBean.setKeyword1(keyword);
        keyword = new Keyword();
        keyword.setKeyValue(checkFailMsgPushRequest.getMchntName());
        wechatMsgPushBean.setKeyword2(keyword);
        keyword = new Keyword();
        keyword.setKeyValue(checkFailMsgPushRequest.getMchntContact());
        wechatMsgPushBean.setKeyword3(keyword);
        keyword = new Keyword();
        keyword.setKeyValue(checkFailMsgPushRequest.getContactPhoneNo());
        wechatMsgPushBean.setKeyword4(keyword);
        ConvertUtil.convertInput(wechatMsgPushBean);

        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.ACCESS_TOKEN, accessToken);
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.TEMPLATE_ID, templateCfg.getTemplateId());
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.JUMP_URL, templateCfg.getTemplateUrl());
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, checkFailMsgPushRequest.getHeader().getTxnNum());
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(dstChannelCfg.getInstId(),
                WechatConfigConstant.WECHAT_CONF_NODE, WechatConfigConstant.WECHAT_PUBLIC_PUSH_MSG_URL);
        if (sysParam == null) {
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }
        xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.DEFINE_HTTP_URL_NODE, sysParam.getParamValue() + "access_token=" + accessToken);
        iReturnCode = schedule.callService(WechatServiceConstant.WECHAT_PUBLIC_CLIENT_SERVICE, 0);

        if (xmlTreeUtil.isExist(WechatTreeNodeConstant.DEFINE_HTTP_URL_NODE)) {
            xmlTreeUtil.deleteXmlTreeNode(WechatTreeNodeConstant.DEFINE_HTTP_URL_NODE);
        }
        if (0 != iReturnCode) {
            rglog.error("调用微信消息推送服务失败，iReturnCode:<{}>", iReturnCode);
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }
        /* 判断调用微信是否成功 */
        String errcode = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_ERR_CODE);
        String errmsg = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_ERR_MSG);
        if (!"0".equals(errcode) && !"40001".equals(errcode)) {
            rglog.error("调用微信公众号服务失败,errcode:<{}>,errmsg:<{}>", errcode, errmsg);
            throw new BizException(errcode, errmsg);
        } else if ("40001".equals(errcode)) {
            /*accessToken失效*/
            accessToken = getAccessToken(dstChannelCfg);
            ConvertUtil.convertInput(wechatMsgPushBean);

            xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.ACCESS_TOKEN, accessToken);
            xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.TEMPLATE_ID, templateCfg.getTemplateId());
            xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.JUMP_URL, templateCfg.getTemplateUrl());
            xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, checkFailMsgPushRequest.getHeader().getTxnNum());
            xmlTreeUtil.setXmlTreeStringValue(WechatTreeNodeConstant.DEFINE_HTTP_URL_NODE, sysParam.getParamValue() + "access_token=" + accessToken);
            iReturnCode = schedule.callService(WechatServiceConstant.WECHAT_PUBLIC_CLIENT_SERVICE, 0);
            if (0 != iReturnCode) {
                rglog.error("调用微信消息推送服务失败，iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
            errcode = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_ERR_CODE);
            errmsg = xmlTreeUtil.getXmlTreeStringValue(WechatTreeNodeConstant.WX_ERR_MSG);
            if (!"0".equals(errcode)) {
                rglog.error("调用微信公众号服务失败,errcode:<{}>,errmsg:<{}>", errcode, errmsg);
                throw new BizException(errcode, errmsg);
            }
        }
        checkFailMsgPushResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        checkFailMsgPushResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        chnlBizResponse.setResult(checkFailMsgPushResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        CheckFailMsgPushResponse mchntApplyRemindMsgPushResponse = (CheckFailMsgPushResponse) response.getResult();
        ConvertUtil.convertInput(mchntApplyRemindMsgPushResponse);
    }
}
